﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ConvertToJs;

namespace Poco2Js
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private List<string> assemblyPaths = new List<string>(); 
        
        public MainWindow()
        {
            InitializeComponent();
        }

        protected void ChooseAssembly(object sender, EventArgs e)
        {
            assemblyPaths.Clear();

            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            dlg.DefaultExt = ".dll";

            dlg.Filter = ".NET Assemblies (.dll)|*.dll";
            dlg.Multiselect = true;


            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                foreach (var file in dlg.FileNames)
                {
                    assemblyPaths.Add(file);

                    var name = System.IO.Path.GetFileName(file);
                    var text = new TextBlock();
                    text.Text = name;
                    Assemblies.Children.Add(text);
                }

            }
            ConvertBtn.IsEnabled = true;
        }


        protected void Convert(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            dlg.Description = "Choose location for classes.";
            dlg.ShowDialog();

            var converter = new Converter();

            foreach (var file in assemblyPaths)
            {
                var assembly = Assembly.LoadFile(file);
                var classes = converter.Convert(assembly);

                TextWriter tw = new StreamWriter(dlg.SelectedPath + "\\" + assembly.GetName().Name+ ".js");

                foreach (var c in classes)
                {
                    tw.Write(c.Content);
                    tw.WriteLine();
                }

                var logItem = new TextBlock();
                    logItem.Text = "Created " + assembly.GetName().Name + ".js";
                    Log.Children.Add(logItem);

                tw.Flush();
                tw.Close();
            }
        }
    }
}
